package com.lijing.mock.web.filter;

import com.lijing.mock.constract.LocalConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 拦截过滤器
 * @author by lijing
 * @date 2019/12/2 0002 11:44
 */
@Slf4j
@WebFilter(filterName = "apiFilter", urlPatterns = "/*",initParams = {@WebInitParam(name = "mock",value = "/mock-platform/*")})
public class ApiFilter implements Filter {

    private static String DISPATCH_URL = "/mock-api/";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       log.info("{},{}",filterConfig.getFilterName(), filterConfig.getInitParameter("mock"));

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String url = httpServletRequest.getRequestURI();
        if (url.startsWith(DISPATCH_URL)) {
            chain.doFilter(request, response);
            return;
        }
        log.info("request url :{}",url);
        MDC.put(LocalConstant.mockUrlKey,url);
        request.getRequestDispatcher("/mock-api/get").forward(request, response);
    }

    @Override
    public void destroy() {

    }
}
